//
//  PCUserGameController.m
//  PhotoCircle
//
//  Created by GL on 15/12/13.
//  Copyright © 2015年 wujungao. All rights reserved.
//

#import "PCUserGameController.h"
#import "PCMeGameCell.h"
#import "SVPullToRefresh.h"
#import "NSDate+Convenience.h"
#import "PCMeStore.h"
#import "PCUserModel.h"
#import "GMTipsHelper.h"
#import "PCOpusDetailVC.h"
#import "PCUserLoginViewController.h"

@interface PCUserGameController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITableViewDelegate,UITableViewDataSource,PCMeGameCellDelegate,UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) PCUserModel *userModel;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) NSMutableArray *gameArray;

@end

@implementation PCUserGameController

-(NSMutableArray *)gameArray{
    if (!_gameArray) {
        _gameArray = [NSMutableArray new];
    }
    return _gameArray;
}

-(PCUserModel *)userModel{
    _userModel = [[PCUserInfoManager sharedUserInfo] readUserInfo];
    return _userModel;
}

- (void)configUI
{
    _pageIndex = 1;
    __weak PCUserGameController *weakSelf = self;
    [self.tableView addPullToRefreshWithActionHandler:^{
        [weakSelf toRefresh];
    }];
    [self.tableView addPullToRefreshWithTriggerHandler:^{
        [weakSelf toTrigger];
    }];
    
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf toLoadMore];
    }];
    
    [self.tableView triggerPullToRefresh];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshGameList) name:@"refreshGameList" object:nil];
}

-(void)refreshGameList{
    [self.tableView triggerPullToRefresh];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configUI];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    MCHiddenBottomView();
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)toRefresh
{
    if (![[PCUserInfoManager sharedUserInfo] checkUserInfo]) {
        [self.tableView.pullToRefreshView stopAnimating];
        return;
    }
    _pageIndex = 1;
    __weak PCUserGameController *weakSelf = self;
    NSString *page = [NSString stringWithFormat:@"%ld",(long)_pageIndex];
    NSDictionary *pDic = @{@"page":page,@"token":self.userModel.userToken};
    [[PCMeStore sharedMeStore] requestUserGameList:pDic successHandler:^(NSInteger responCode,NSArray *array){
        
        [weakSelf.tableView.pullToRefreshView stopAnimating];
        if (responCode == API_RESPONSE_OK) {
            [weakSelf.gameArray removeAllObjects];
            _pageIndex++;
            
            [weakSelf.gameArray addObjectsFromArray:array];
            [weakSelf.tableView reloadData];
        }else if(responCode == API_RESPONSE_INVALIDTOKEN){
            // 加载
            [self tipAlertView];
        }else{
            // 加载失败
        }
    } errorHandler:^{
        [weakSelf.tableView.pullToRefreshView stopAnimating];
        [GMTipsHelper showBadNetwork];
    }];
}

- (void)toTrigger
{
    NSString *lastUpdateTime = [UserDefaults_GetObject(NSStringFromClass([self class])) sinceNowDescription];
    if(!lastUpdateTime.length)
        lastUpdateTime = NSLocalizedString(STR_NeverRefresh, );
    NSString *lastUpdateStr = PCStrFormat(@"%@%@", NSLocalizedString(STR_LastAt, ), lastUpdateTime);
    [self.tableView.pullToRefreshView setSubtitle:lastUpdateStr forState:SVPullToRefreshStateAll];
}

- (void)toLoadMore
{
    NSString *page = [NSString stringWithFormat:@"%ld",(long)_pageIndex];
    NSDictionary *pDic = @{@"page":page,@"token":self.userModel.userToken};
    __weak PCUserGameController *weakSelf = self;
    [[PCMeStore sharedMeStore] loadMoreUserGameList:pDic successHandler:^(NSInteger responCode,NSArray *array){
        
        [weakSelf.tableView.infiniteScrollingView stopAnimating];
        if (responCode == API_RESPONSE_OK) {
            if (array.count > 0) {
                _pageIndex++;
                [self.gameArray addObjectsFromArray:array];
                [self.tableView reloadData];
            }else{
                // 没有更多
            }
        }else{
        }
    } errorHandler:^{
        [weakSelf.tableView.infiniteScrollingView stopAnimating];
        [GMTipsHelper showBadNetwork];
    }];
}


-(void)tipAlertView
{
    if (iOS(8.0)) {
        
        UIAlertController * cancleAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的账号已在其他设备登录，是否重新登录?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[PCUserInfoManager sharedUserInfo] cleanLocalUserInfo];
            [self jumpToLogin];
        }];
        
        UIAlertAction *cancleAcion = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self backEvent:nil];
        }];
        [cancleAlert addAction:okAciton];
        [cancleAlert addAction:cancleAcion];
        [self presentViewController:cancleAlert animated:YES completion:^{
        }];
    }else{
        
        UIAlertView *cancleAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否删除图片" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        //cancleAlert.tag =CancleTag;
        cancleAlert.delegate = self;
        [cancleAlert show];
    }
}

#pragma mark -
#pragma mark -PCLogoutCellDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [[PCUserInfoManager sharedUserInfo] cleanLocalUserInfo];
        [self jumpToLogin];
    }else{
        [self backEvent:nil];
    }
}

-(void)jumpToLogin{
    
    UIStoryboard *loginS=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];;
    PCUserLoginViewController *loginVC=[loginS instantiateViewControllerWithIdentifier:@"PCUserLoginVC"];
    //
    [self.navigationController pushViewController:loginVC animated:YES];
}
#pragma mark -
#pragma mark - UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.gameArray count];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *questionCellID = @"PCMeGameCell";
    PCMeGameCell *cell = [tableView dequeueReusableCellWithIdentifier:questionCellID];
    PCUserGameModel *gModel = self.gameArray[indexPath.row];
    [cell configCellWithModel:gModel];
    cell.delegate = self;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    PCUserGameModel *gModel = self.gameArray[indexPath.row];
    PCOpusDetailVC * opusDetailVC = [PCOpusDetailVC controllerInStoryboard:@"Main" identifier:@"PCOpusDetailVC"];
    opusDetailVC.workUuid = gModel.gUUID;
    [self.navigationController pushViewController:opusDetailVC animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 109;
}

//pushGamePayVC
#pragma mark -
#pragma mark -PCGameCellDelegate
-(void)selectedLeftButton:(PCUserGameModel *)gMode
{
    // 放弃参赛
    NSDictionary *pDic = @{@"uuid":gMode.gUUID,@"token":self.userModel.userToken};
    [[PCMeStore sharedMeStore] giveUpGame:pDic successHandler:^(NSInteger responCode, PCUserGameModel *model){
        
        if (responCode == API_RESPONSE_OK) {
            
            gMode.gChooseMark = model.gChooseMark;
            gMode.gChooseState = model.gChooseState;
            gMode.gState = model.gState;
            gMode.gMarkGame = model.gMarkGame;
            
            [self.tableView reloadData];
        }else{
            [GMTipsHelper showFail:@"请求失败"];
        }
    } errorHandler:^{
        [GMTipsHelper showBadNetwork];
    }];
}

-(void)selectedRightButton:(PCUserGameModel *)gModel
{
    // 跳转支付
    [[PCMeStore sharedMeStore] selectedIndexGameModel:gModel];
    [self performSegueWithIdentifier:@"pushGamePayVC" sender:self];
}

-(void)upLoadRealImage
{
    //相册上传
    UIImagePickerController *imagePickerVC=[[UIImagePickerController alloc] init];
    imagePickerVC.delegate=self;
    imagePickerVC.allowsEditing = YES;
    imagePickerVC.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

#pragma mark - image picker delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    PCUserGameModel *gModel = [PCMeStore sharedMeStore].mGameModel;
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
    NSDictionary *dictionary = @{@"token":self.userModel.userToken,@"uuid":gModel.gUUID};
    [GMTipsHelper showLoading];
    [[PCMeStore sharedMeStore] upLoadRealImage:dictionary image:imgData successHandler:^(NSInteger responCode){
        if (responCode == API_RESPONSE_OK) {
            [GMTipsHelper showSuccess:@"上传成功"];
            [self.tableView triggerPullToRefresh];
        }else{
            [GMTipsHelper showFail:@"上传失败"];
        }
    } errorHandler:^{
        [GMTipsHelper showBadNetwork];
    }];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    //[self uploadImage:image];
}

#pragma mark -
#pragma mark -Button Event

- (IBAction)backEvent:(UIButton *)sender {
    [GMTipsHelper showDismiss];
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshGameList) name:@"refreshGameList" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"refreshGameList" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
@end
